<?php

function googleCache($id,$token,$fmt){
  $ytURL = "http://youtube.com/get_video?video_id=" . $id . "&t=" . $token. "&asv=&fmt=" . $fmt;
  //	$ytURL = "http://www.youtube.com/get_video?t=vjVQa1PpcFNqEf7mGOw0Gk9PLbFvsqu0bV2adxLsaKQ=&noflv=1&fmt=34&el=detailpage&video_id=a4D1lIZSck8&asv=3";

  $headers = get_headers($ytURL,1);

  //	print_r($headers);
  $status = explode(" ",$headers['1']);
  if($status[1] == "200"){
    if(!is_array($headers['Location'])) {
      $videoURL = $headers['Location'];
    }else{
      foreach($headers['Location'] as $header){
        if(strpos($header,"googlevideo.com") != false){
          $videoURL = $header;
          break;
        }
      }
    }
    return $videoURL;
  }else{
    return "";
  }
}

function youtubeData($ido){
  global $ids;
 $content = file_get_contents("http://www.youtube.com/watch?v=".$ido);
 preg_match('~\"t\":\s*\"([^\"]*)\"~',$content,$videoTicketMatches);
        $ticket=$videoTicketMatches[1];
 preg_match("/\"fmt_url_map\":\s*\"([^\"]*)\"/",$content,$formatmatches);
 $videoFormats=($formatmatches!=null)?$formatmatches[1]:"";
 $sep1="%2C";
 $sep2="%7C";
  if (stripos($videoFormats,",")>-1) { // new UI
    $sep1=",";
    $sep2="|";
  }
  $videoFile="";
  $vfmt=Array();
  $videoFormatsGroup=explode($sep1,$videoFormats);
  for ($i=0;$i<count($videoFormatsGroup);$i++){
    $videoFormatsElem=explode($sep2,$videoFormatsGroup[$i]);
        $videoUrl=preg_replace("~\\\/~", "/", $videoFormatsElem[1]);
switch($videoFormatsElem[0]){
  case "18":
                if (!in_array(35, $vfmt)) $videoFile.= '<a data-role="button" href="javascript:nmt.play(&#34;'.$videoUrl.'&#34;)" vod>view</a>';
                $vfmt[]=18;
                $ids[]=$videoUrl;
                break;
 case "35":
                if (!in_array(18, $vfmt)) $videoFile.= '<a data-role="button" href="javascript:nmt.play(&#34;'.$videoUrl.'&#34;)" vod>view</a>';
                $vfmt[]=35;
                break;
 case "22":
                $videoFile.= '<a data-role="button" href="javascript:nmt.play(&#34;'.$videoUrl.'&#34;)" vod>view in 720p</a>';
                break;
 case "37":
                $videoFile.= '<a data-role="button" href="javascript:nmt.play(&#34;'.$videoUrl.'&#34;)" vod>view in 1080p</a>';
                break;
 default:
    //$videoFile.= '<a href="http://youtube.com/get_video?video_id='.$ido.'&t='. $ticket.'&asv=&fmt=18" vod>[view]</a>';
 }
 }
return $videoFile;
}

function youtubeDatalist($ido){
  $content = file_get_contents("http://www.youtube.com/watch?v=".$ido, false, NULL, -1,18432);
  $one=stripos($content,'length_seconds');
  $content=substr($content,$one);
  $one2=stripos($content,'">');
  parse_str($content);


  if($t != ""){
    $fmts=explode(",",$fmt_map,3);
    $fmts[0]=substr($fmts[0],0,2);
    $fmts[1]=substr($fmts[1],0,2);
    $fmts[2]=substr($fmts[2],0,2);
    if($fmts[0]==37 or $fmts[0]=='37') {
      if($fmts[1]==22 or $fmts[1]=='22') $videoFile.= 'http://youtube.com/get_video?video_id='.$ido.'&t='.$t.'&asv=&fmt=22';
      return $videoFile;
    }

    if($fmts[0]==22 or $fmts[0]=='22') {
      if($fmts[0]==22 or $fmts[0]=='22') $videoFile.= 'http://youtube.com/get_video?video_id='.$ido.'&t='.$t.'&asv=&fmt=22';
      return $videoFile;
    }

    if($fmts[0]==35 or $fmts[0]=='35') $videoFile= 'http://youtube.com/get_video?video_id='.$ido.'&t='.$t.'&asv=&fmt=18';
    // echo "<br>".$id."=".$fmts[0];

    if($fmts[0]=='18' or $fmts[0]==18) $videoFile= 'http://youtube.com/get_video?video_id='.$ido.'&t='.$t.'&asv=&fmt=18';

    if ($fmts[0]=='34' or $fmts[0]==34) {
      $videoFile="";
      return $videoFile;
    }
  }  else if ($status=='failed') {
    $videoFile="";
  } else {
    $videoFile= 'http://youtube.com/get_video?video_id='.$ido.'&t='.$t.'&asv=&fmt=18';
  }
  return $videoFile;
}

function echoPlaylist($ids){
  global $files;
  $tst=explode(":",$ids);
  header("Content-Type: x-foo/x-bar");
  header('Content-Description: File Transfer');
  header('Content-Transfer-Encoding: binary');
  header('Content-Disposition: filename="playlist.jsp"');
  $output="";
  foreach ($tst as $id){
    $url=youtubeDatalist($id);
    if(strlen($id)>3) $output.=$id."|0|0|".$url."|\n\r\n";
  }
  echo $output;
}
////////////////////////////////
//$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos?vq=sand&search_sort=video_avg_rating&racy=include&max-results=5');
//////////////////////////////////////

function echoVideoList($searchstring) {
  global $files;

  $plurl="?plist=yes&ids=";
  $files=Array();

  $xml = simplexml_load_file($searchstring);
  $result=$xml->entry;

  //echo '<div class="ui-grid-a">';
  echo '<ul data-role="listview">';
  $i=0;
  foreach ($result as $entry) {
    $i++;
    $VideoId=substr($entry->id,42);
    $Title=$entry->title;

    $media = $entry->children('http://search.yahoo.com/mrss/');
    $attrs = $media->group->thumbnail->attributes();
    $Thumnail= $attrs['url'][0];

    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->duration->attributes();
    $seconds = (double)$attrs['seconds'];
    $time_m=floor($seconds/60);
    $time_s =fmod($seconds,60);

    $Time=sprintf("%02d:%02d", $time_m, $time_s);

    $yt=$entry->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->statistics->attributes();
    $viewCount = $attrs['viewCount'];
    $gd = $entry->children('http://schemas.google.com/g/2005');

    if ($gd->rating) {
      $attrs = $gd->rating->attributes();
      $rating = sprintf("%0.4f", $attrs['average']);
    } else {
      $rating = 0;
    }

    //$url=youtubeData($VideoId);
    $urlVideoId = urlencode($VideoId);
    $urlTitle = urlencode($Title);
    $urlThumbnail = urlencode($Thumnail);
    $urlTime = urlencode($Time);
    $urlViews = urlencode($viewCount);
    $urlRating = urlencode($rating);

    //if (strlen($url)<3) continue;
    //$plurl.=$VideoId.":";

    /*
    $output=<<<END
    <div class="ui-bar ui-bar-c">
      <h3 class="ui-li-heading">${Title}</h3>
      <p class="ui-li-desc"><br/>Duration: ${Time} Views: ${viewCount} Rating: ${rating}</p>
      <h3>${url}</h3>
    </div>
END;
*/
    $output = <<<END
    <li>
      <img src="${Thumnail}" />
      <h4 class="forcewrap"><a href="ytdetail.php?vid=${urlVideoId}&t=${urlTitle}&thm=${urlThumbnail}&tm={$urlTime}&v={$urlViews}&r={$urlRating}">${Title}</a></h4>
      <p class="forcewrap">${Time} | ${viewCount} | ${rating}</p>
    </li>
END;
    echo $output;
  }
  //echo '</div>';
  echo '</ul>';
}
?>